﻿#include "tabbarwidget.h"
#include "ui_tabbarwidget.h"

TabBarWidget::TabBarWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TabBarWidget)
{
    ui->setupUi(this);

    tab_btns = new QList<QWidget*>();

    if(currentTab == nullptr){
//        CustomWebView *webView = createBackgroundTab();
//        webView->load(QUrl("https://www.baidu.com"));
//        createTab();
    }
}

TabBarWidget::~TabBarWidget()
{
    delete ui;
}

// 新建标签页
CustomWebView * TabBarWidget::createTab()
{

    TabBarButton *tabBtn = new TabBarButton(this);
    // 设置对应的webview
    CustomWebView *webView = new CustomWebView(nullptr);

    CustomWebPage *page = new CustomWebPage(this->profile);
//    page->setDevToolsPage(devPage->page());
    connect(page, &QWebEnginePage::authenticationRequired, this, [=](const QUrl& url, QAuthenticator *authenticator){
        qDebug() << "receive authenticator: " << url << authenticator->user() << authenticator->password();
    });
    connect(page, &QWebEnginePage::linkHovered, this, [=](const QString &url){
        qDebug() << "linkhover: " << url;
        emit linkHover(url);
    });

    connect(webView, &CustomWebView::loadFinished, this, [=]{
        qDebug() << "start url: " << webView->url();
        // 加载网页时更新输入栏url
        emit changeUrl(webView->url().toString());
        // 更新历史记录
        HistoryManager::getInstance().addHistory(UrlInfo(page->title().toStdString().c_str(), "", page->url().toString().toStdString().c_str()));
        // 更新提示
        tabBtn->updateWhatIs(webView->url().toString());
        // 加载完成进行网页内容检测
        page->toHtml([=](const QString &html){
//            qDebug() << "get page source:" << html;
            // 提交后台检测服务器进行检测
            QtHttpUtils *utils = new QtHttpUtils();
            QString checkUrl = QString(ConfigManager::getInstance().getServerPath().c_str()) + "/check";
            QJsonObject param;
            param.insert("url", page->url().toString());
            param.insert("text", html);     //
            param.insert("contentDetect", true);       // 同时进行网页内容检测
            QJsonObject resp = utils->post(QUrl(checkUrl), param);
            // 通知管理器实例化，用于显示通知提示消息
            NotifyManager *manager = new NotifyManager(nullptr);
            manager->setMaxCount(5);
            manager->setDisplayTime(5000);
            manager->setNotifyWndSize(500, 200);
            if(resp.value("resourceTamper").toBool()){
                // 存在资源被篡改的危险
                manager->notify("危险警告", "检测到网页内容与缓存不一致，该网页内容可能已经被篡改,建议谨慎访问该网页");
            }else if(resp.value("dangerCode").toBool()){
                // 网页存在恶意脚本
                manager->notify("危险警告", "该网页可能存在恶意攻击的行为，keyword:" + resp.value("dangerKeyWord").toString());
            }

            // 插件执行
            const QVector<PluginInfo> plugins = PluginManager::getInstance().getPlugins();
            for(int i = 0; i < plugins.size(); i++){
                PluginInfo pluginInfo = plugins[i];
                qDebug() << pluginInfo.name << "执行";
                page->runJavaScript(pluginInfo.code);
                qDebug() << pluginInfo.name << "执行完成";
            }
        });

    });

    webView->setPage(page);
    webView->show();

//    // 绑定开发者页面(F12触发)
//    QWebEngineView *devView = new QWebEngineView();
//    page->setDevToolsPage(devView->page());
//    devView->show();
    tabBtn->view_widget = webView;
    webView->load(QUrl("https://www.baidu.com"));
    // 关闭tab事件
    connect(tabBtn, &TabBarButton::remove, this, &TabBarWidget::removeTab);
    // 点击切换事件
    connect(tabBtn, &TabBarButton::change, this, &TabBarWidget::clickTab);
    qDebug() << "create web view";

    qDebug() << "create web view finish";
    // 绑定网页加载事件
    connect(webView, &CustomWebView::loadFinished, tabBtn, &TabBarButton::loadWebViewIcon);
    connect(webView, &CustomWebView::iconChanged, tabBtn, &TabBarButton::setTabIcon);
    connect(webView, &CustomWebView::titleChanged, tabBtn, &TabBarButton::setTabText);
//    setCurrentWebView(webView);
    qDebug() << "set up webview finish";
//    webView->hide();
    this->ui->tab_list_widget->layout()->addWidget(tabBtn);
    tab_btns->append(tabBtn);
    qDebug() << "create tab" << tabBtn->tab_button << tabBtn->view_widget;
    clickTab(tabBtn);
    return webView;
}

// 当前标签页上加载
CustomWebView *TabBarWidget::createBackgroundTab()
{
//    TabBarButton *tabBtn = new TabBarButton(this);
//    // 关闭tab事件
//    connect(tabBtn, &TabBarButton::remove, this, &TabBarWidget::removeTab);
//    // 点击切换事件
//    connect(tabBtn, &TabBarButton::change, this, &TabBarWidget::clickTab);

    // 设置对应的webview
    CustomWebView *webView = new CustomWebView(currentTab);
    CustomWebPage *page = new CustomWebPage(this->profile);
    webView->setPage(page);
    // 绑定网页加载事件
    connect(webView, &CustomWebView::loadFinished, currentTab, &TabBarButton::loadWebViewIcon);
    connect(webView, &CustomWebView::iconChanged, currentTab, &TabBarButton::setTabIcon);
    connect(webView, &CustomWebView::titleChanged, currentTab, &TabBarButton::setTabText);
    currentTab->view_widget = webView;
   /* this->ui->tab_list_widget->layout()->addWidget(currenTab);
    tab_btns->append(currenTab)*/;
//    webView->load(QUrl("https://www.baidu.com"));
//    clickTab(currentTab);
    return webView;
}



void TabBarWidget::removeTab(TabBarButton *tab_ptr){
//    if(tab_btns->size() == 1)return;
    QWidget *ptr = static_cast<QWidget*>(tab_ptr);
    int idx = tab_btns->indexOf(ptr);
    qDebug() << "idx = " << idx << ", size = " << tab_btns->size();
    tab_btns->removeAt(idx);
    this->ui->tab_list_widget->layout()->removeWidget(ptr);
//    tab_ptr->setParent(nullptr);        // 可以从布局中移除，但不能直接将内存释放，主窗口中还在使用
//    delete tab_ptr->view_widget;
//    delete tab_ptr;
    emit removeView(tab_ptr);
}

void TabBarWidget::clickTab(TabBarButton *tab_ptr){
    if(currentTab == tab_ptr)return;
    if(currentTab != nullptr){
        currentTab->setDefaultTabStyle();
    }
    qDebug() << "active tab start";
    tab_ptr->setActiveTabStyle();
    qDebug() << "active tab" << tab_ptr << tab_ptr->view_widget;
    currentTab = tab_ptr;
    emit changeView(currentTab);
    emit changeUrl(this->currentTab->view_widget->url().toString());
}

void TabBarWidget::setCurrentWebView(CustomWebView *view)
{
    if(currentTab == nullptr)return;
    currentTab->view_widget = view;
}

void TabBarWidget::addTab(CustomWebView *webView)
{
    TabBarButton *tabBtn = new TabBarButton(this);
    // 关闭tab事件
    connect(tabBtn, &TabBarButton::remove, this, &TabBarWidget::removeTab);
    // 点击切换事件
    connect(tabBtn, &TabBarButton::change, this, &TabBarWidget::clickTab);

    // 设置对应的webview
//    CustomWebView *webView = new CustomWebView(tabBtn);
    CustomWebPage *page = new CustomWebPage(this->profile);
    webView->setPage(page);
    // 绑定网页加载事件
    connect(webView, &CustomWebView::loadFinished, tabBtn, &TabBarButton::loadWebViewIcon);
    connect(webView, &CustomWebView::iconChanged, tabBtn, &TabBarButton::setTabIcon);
    connect(webView, &CustomWebView::titleChanged, tabBtn, &TabBarButton::setTabText);

    tabBtn->view_widget = webView;
    this->ui->tab_list_widget->layout()->addWidget(tabBtn);
    tab_btns->append(tabBtn);
    webView->load(QUrl("https://www.baidu.com"));
    clickTab(tabBtn);
}

void TabBarWidget::setTabIcon()
{

}

void TabBarWidget::on_add_tab_btn_clicked()
{
    createTab();
}

